<?php
require_once dirname(__FILE__) . '/common/common.inc.php';
require_once dirname(__FILE__) . "/database/$database/database.inc.php";
  
header('Content-Type: text/plain');

$class = MiscUtils::getParam('name', NULL);
$objectsToAddOrUpdate = json_decode(MiscUtils::getParam('o', NULL));
$objectsToRemove = json_decode(MiscUtils::getParam('r', NULL));
$email = json_decode(MiscUtils::getParam('e', NULL));

$orm = classToOrm($class);
if ($orm) {
  try {
    $myManager->start_t();
    foreach ($objectsToAddOrUpdate as &$object) {
      if (isset($object->id)) {
        $orm->update($myManager, $object);
      } else {
        $orm->add($myManager, $object);
      }
    }
    foreach ($objectsToRemove as &$object) {
      $orm->remove($myManager, $object);
    }
    
    if ($email && $email->addr != '' ) {
      require_once dirname(__FILE__) . '/library/phpMailer/class.phpmailer.php';
      $mailer = new PHPMailer();
      $mailer->IsSMTP();
      $mailer->Host = MAIL_HOST;
      if (MAIL_SMTP) {
        $mailer->SMTPAuth = MAIL_SMTP;
      }
      $mailer->Username = MAIL_USER;
      $mailer->Password = MAIL_PASSWORD;
      $mailer->From = MAIL_FROM;
      $mailer->FromName = MAIL_NAME;
      $mailer->Body = $email->content;
      $mailer->Subject = $email->title;
      
//      $mailer = new PHPMailer();
//      $mailer->IsSMTP();
//      $mailer->Host = 'mx.hosting.isx.net.nz';
//      //$mailer->SMTPAuth = true;
//      $mailer->Username = 'dreamlife.customerservice@dlmanage.co.nz';
//      $mailer->Password = 'luckybox4mail';
//      $mailer->From = 'dreamlife.customerservice@gmail.com';
//      $mailer->FromName = 'Dreamlife Publish System';
//      $mailer->Body = $email->content;
//      $mailer->Subject = $email->title;
      if ($email->addr != '') {
        $mailer->AddAddress($email->addr);
      }
      if (!$mailer->Send()) {
        echo ERROR_SIGN . $mailer->ErrorInfo;
        return;
      }
    }
    
    $myManager->commit_t();
    echo json_encode(array());
  } catch (PDOException $e) {
    echo ERROR_SIGN . $e->getMessage();
  }
}
?>